# -*- coding: utf-8 -*-
from Kamaelia.Chassis.Graphline import Graphline
from Kamaelia.Util.Backplane import Backplane,PublishTo,SubscribeTo
from Axon.Component import makeOutbox
#import pygame
#import random
from Command import *
from numpy import *
import os
#from Kamaelia.UI.Pygame.EventHandler import EventHandler
from Kamaelia.UI.Pygame.KeyEvent import KeyEvent
#from Kamaelia.Internet.TCPClient import TCPClient
from Kamaelia.Chassis.ConnectedServer import SimpleServer
from pygame.locals import *
from Kamaelia.Util.Console import ConsoleEchoer #, ConsoleReader
from Axon.Component import component

from GameState import GameState#, Player
from Networking import Commandizer, Packetizer, CreatePlayerHandler

# Create backplanes
backplaneCommandInput = Backplane("CommandInput")
backplaneCommandOutput = Backplane("CommandOutput")
backplaneCommandInput.activate()
backplaneCommandOutput.activate()

gameState = GameState()
gameState.activate()

class PlayerWriter(component):
    
    Inboxes = {"writeInbox" : "",            
               "addPlayerInbox" : "",
               "control" : ""}
    Outboxes = {"signal" : "",}
    
    def __init__(self):
        self.__super.__init__() # Must always happen!
        
    def main(self):        
        while not self.shutdown():
            yield 1
            
            while self.dataReady("addPlayerInbox"):
                data = self.recv("addPlayerInbox")
                player_box = "writeOutbox" + str(data[0])
                sink = data[1]
                self.outboxes[player_box] = makeOutbox()
                self.link((self,player_box), sink)
                    
            while self.dataReady("writeInbox"):
                data = self.recv("writeInbox")
                player_box = "writeOutbox" + str(data[0])
                #if player_box in self.outboxes:
                self.send(data[1:],player_box)
                                        
    def shutdown(self):
        if self.dataReady("control"):
            msg = self.recv("control")
            if(isinstance(msg, Axon.Ipc.producerFinished)):
                self.send(msg,"signal")
                return True
            return False
         
class BejeweledCreatePlayerHandler(CreatePlayerHandler):
    def __call__(self,*argl):
        pl = CreatePlayerHandler.__call__(self,*argl)
        proto = Graphline(PLAYER_HANDLER  = pl,
                          BP_INPUT = PublishTo("CommandInput"),
                          BP_OUTPUT = SubscribeTo("CommandOutput"),
                          linkages = {
                                      # Bind grpahline inbox/outbox to PLAYER_HANDLER
                                      ("PLAYER_HANDLER", "outbox") : ("self", "outbox"),
                                      ("self", "inbox") : ("PLAYER_HANDLER", "inbox"),
                                      
                                      # Bind command inbox/outbox to backplanes
                                      ("BP_OUTPUT","outbox") : ("PLAYER_HANDLER", "commandInbox"),
                                      ("PLAYER_HANDLER", "commandOutbox") : ("BP_INPUT","inbox"),
                                    }
                          )
        return proto
    
Graphline(BP_INPUT = SubscribeTo("CommandInput"),
          BP_OUTPUT = PublishTo("CommandOutput"),
          PLAYER_WRITER = PlayerWriter(),
          GAME_STATE = gameState,
          linkages = {
                        # Bind grpahline inbox/outbox to PLAYER_HANDLER
                        ("BP_INPUT", "outbox") : ("GAME_STATE", "CommandInbox"),
                        ("GAME_STATE", "cmdBroadcast") : ("BP_OUTPUT", "inbox"),
                        
                        # Direct command communication
                        ("GAME_STATE", "cmdDirect") : ("PLAYER_WRITER", "writeInbox"),
                        ("GAME_STATE", "cmdDirectInit") : ("PLAYER_WRITER", "addPlayerInbox"),
                    }
          ).activate()
          
                
server=SimpleServer(protocol=BejeweledCreatePlayerHandler(),
                    port=6662).run()


